<template>
  <div class="context-menu" ref="menuRef">
    <ul>
      <li
        @click="item.action()"
        class="context-menu-item flex justify-between align-center"
        v-for="item in actions"
        :key="item.key"
      >
        <span class="text pl-1">{{ operationText[item.key].text }}</span>
        <span class="text pr-1">{{ operationText[item.key].shortcut }}</span>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted } from "vue";
import { map, pick } from "lodash-es";
import dataOperation, { operationText } from "@/plugins/dataOperations";
export default defineComponent({
  setup(props, context) {
    let componentId = ref<string>("");
    let menuRef = ref<HTMLElement | null>(null);
    // 提取
    const operations = pick(dataOperation(componentId), [
      "copy",
      "paste",
      "delete",
      "cancel",
    ]);
    // 转列表
    const actions = map(operations, (val, key) => {
      return {
        key,
        action: val,
      };
    });
    let triggerContextMenu = (e: MouseEvent) => {
      e.preventDefault();
      const domElement = menuRef.value as HTMLElement;
      // @ts-ignore
      // 获取右键点击的组件
      let currentId = e.target.dataset["id"];
      if (currentId) {
        componentId.value = currentId;
        context.emit("onSelecte", currentId);
        domElement.style.display = "block";
        domElement.style.top = e.pageY + "px";
        domElement.style.left = e.pageX + "px";
      }
    };

    let handleClick = () => {
      const domElement = menuRef.value as HTMLElement;
      domElement.style.display = "none";
    };

    onMounted(() => {
      document.addEventListener("contextmenu", triggerContextMenu);
      document.addEventListener("click", handleClick);
    });
    onUnmounted(() => {
      document.removeEventListener("contextmenu", triggerContextMenu);
      document.addEventListener("click", handleClick);
    });
    return {
      menuRef,
      actions,
      operationText,
    };
  },
});
</script>

<style lang="scss" scoped>
.context-menu {
  width: 220px;
  border: 1px solid rgb(204, 204, 204);
  position: fixed;
  display: none;
  z-index: 9999;
  background: #fff;
}
.context-menu-item:hover {
  background: #efefef;
  .text {
    color: #1890ff;
  }
}
.text {
  height: 40px;
  line-height: 40px;
  color: rgba(0, 0, 0, 0.45);
}
</style>
